package es.udc.emarketapp.emarket.model.categoryFacade.actions;

import es.udc.emarketapp.emarket.model.category.dao.SQLCategoryDAO;
import es.udc.emarketapp.emarket.model.category.dao.SQLCategoryDAOFactory;
import es.udc.emarketapp.emarket.model.category.vo.CategoryVO;
import es.udc.fbellas.j2ee.util.exceptions.InstanceNotFoundException;
import java.sql.Connection;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.NonTransactionalPlainAction;
import java.util.ArrayList;
import java.util.List;

public class GetCategoryRouteAction implements NonTransactionalPlainAction {

    private Long idCat;

    public GetCategoryRouteAction(Long idCat) {
        this.idCat = idCat;
    }

    public Object execute(Connection connection)
            throws InstanceNotFoundException, InternalErrorException {

        SQLCategoryDAO categoryDAO = SQLCategoryDAOFactory.getDAO();

        List<CategoryVO> currentCat = new ArrayList<CategoryVO>();

        CategoryVO cat = categoryDAO.findById(connection, idCat);

        while (cat.getCatPadre() > 0) {
            CategoryVO catPadre;

            catPadre = categoryDAO.findById(connection, cat.getCatPadre());
            currentCat.add(cat);
            cat = catPadre;
        }

        List<CategoryVO> currentCatOrd = new ArrayList<CategoryVO>();
        while (!currentCat.isEmpty()) {
            int index = currentCat.size();
            currentCatOrd.add(currentCat.get(index - 1));
            currentCat.remove(index - 1);
        }

        return currentCatOrd;

    }
}
